// 引入react相关
import React from 'react';
// 引入antd组件
import { Col, Row, message, Card, notification } from 'antd';
// 引入工具类
import PropTypes from 'prop-types';
import { inject, observer } from 'mobx-react';

import User from '../store/user_store'
import { post, get, preventXss } from '../util/comm';
import LoadMore from './load_more';
import CommentsArea from './comments_area'
import { commentUrl, collectionUrl, postCommentUrl } from '../util/constant';

// 初始化工具类
@inject((stores) => {
  const store = {
    userStore: stores.userStore,
  }
  return store
})

@observer
class CommComments extends React.Component {
  constructor() {
    super();
    this.state = {
      page: 1,
      total: '',
      comments: [],
      isLoading: true,
    }
    this.getMoreComments = this.getMoreComments.bind(this)
    this.doComment = this.doComment.bind(this)
    this.collect = this.collect.bind(this)
  }
  componentDidMount() {
    this.getComments(this.state.page);
  }
  // 获取评论,count为一次性显示的评论数
  getComments(page) {
    const param = {
      newsId: this.props.newsId,
      page,
      pageSize: this.props.pageSize,
    }
    const url = commentUrl;
    get(url, param).then((res) => {
      const result = res.data
      if (res.status === 200 && result.code === 1) {
        const commentList = result.data.length > 1 ? result.data.reverse() : result.data;
        this.setState({
          comments: this.state.comments.concat(commentList),
          total: result.total,
          isLoading: false,
        })
      }
    }).catch((msg) => {
      message.error(`出错了${msg}`);
    })
  }
  // 获取更多的评论
  getMoreComments() {
    this.setState({
      page: this.state.page + 1,
      isLoading: true,
    })
    this.getComments(this.state.page + 1);
  }
  // 发表评论
  doComment(content) {
    return new Promise((resolve) => {
      // 用户没有登录，无法评论，提示信息并return
      const userId = this.props.userStore.userInfo.id
      if (!userId) {
        message.error('请先登录再评论');
        return;
      }
      if (!content) {
        message.error('请输入评论内容');
        return;
      }
      // 简单的防xss攻击
      content = preventXss.html2Escape(preventXss.removeHtmlTab(content));
      // 提交评论的参数
      const param = {
        newsId: this.props.newsId,
        userId,
        content,
      }
      const url = postCommentUrl;
      // 提交评论
      post(url, param).then((res) => {
        if (res.status === 200) {
          if (res.data.code === 1) {
            message.success('评论成功');
            this.setState({
              comments: [],
              isLoading: true,
            })
            this.getComments(1);
            resolve()
          } else if (res.data.code === 10) {
            this.props.userStore.clearUserInfo();
            message.error('请登陆后再评论')
          } else {
            message.error(res.data.message);
          }
        } else {
          message.error(res.data.message);
        }
      }).catch((msg) => {
        message.error(msg)
      })
    })
  }

  // 收藏
  collect() {
    const userId = this.props.userStore.userInfo.id
    const { newsId } = this.props
    if (!userId) {
      message.error('请先登录再评论');
      return;
    }
    const param = {
      newsId,
      userId,
    }
    const url = collectionUrl;
    // 用户没有登录,提示信息
    if (!param.userId) {
      notification.error({
        message: '小白新闻提醒',
        description: '请先登录',
      })
      return;
    }
    // 文章id存在,用户已登录才能收藏
    if (param.newsId && param.userId) {
      post(url, param).then((res) => {
        if (res.status === 200) {
          if (res.data.code === 1) {
            notification.success({
              message: '小白新闻提醒',
              description: '收藏该文章成功',
            })
          } else if (res.data.code === 10) {
            this.props.userStore.clearUserInfo();
            notification.error({
              message: '小白新闻提醒',
              description: '请登陆后再进行收藏',
            })
          } else {
            message.error(res.data.message);
          }
        } else {
          message.error(res.data.message);
        }
      })
    }
  }
  render() {
    return (
      <div className="comments" ref="comments">
        <Row>
          <h3>热门评论</h3>
          <Col span={24}>
            { this.state.comments.length ?
              this.state.comments.map(commentsItem => (
                <div
                  key={commentsItem.createTime}
                  style={{ margin: '10px 0' }}
                >
                  <Card title={commentsItem.nickName} extra={commentsItem.createTime}>
                    {commentsItem.content}
                  </Card>
                </div>
                )) : ''
            }
            <LoadMore
              isLoading={this.state.isLoading}
              hasMore={this.state.comments.length < this.state.total}
              getMore={this.getMoreComments}
            />
          </Col>
        </Row>
        <CommentsArea submit={this.doComment} collect={this.collect} />
      </div>
    )
  }
}

export default CommComments;
CommComments.propTypes = {
  newsId: PropTypes.number,
  pageSize: PropTypes.number,
  userStore: PropTypes.instanceOf(User),
}
